package com.example.word_demo.util;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.util.PoitlIOUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author benjamin_5
 * @Description
 * @date 2024/11/24
 */
@Slf4j
public class WordUtil {

    /**
     *
     * @param templatePath
     * @param dataMap word数据，格式参考 https://deepoove.com/poi-tl/#_data_model%E6%95%B0%E6%8D%AE
     * @param response
     */
    public static void downloadWord(String templatePath, String outFileName, Map<String, Object> dataMap, HttpServletResponse response) {
        InputStream inputStream = null;
        XWPFTemplate template = null;
        OutputStream out = null;
        BufferedOutputStream bos = null;
        try{
            inputStream = WordUtil.class.getClassLoader().getResourceAsStream(templatePath);
//            inputStream = new FileInputStream(templatePath);
            if(inputStream == null){
                throw new RuntimeException("输入文件为空: "+templatePath);
            }
            template = XWPFTemplate.compile(inputStream).render(dataMap);
            // 输出
            outFileName = new String(outFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + outFileName);

            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            template.write(bos);
            bos.flush();
            out.flush();
        }catch (Exception e){
            log.error("word生成失败："+ ExceptionUtils.getStackTrace(e));
            throw new RuntimeException(e);
        }finally {
            PoitlIOUtils.closeQuietlyMulti(inputStream, template, bos, out);
        }
    }

    public static void writeWord(String templatePath, String outFileName, Map<String, Object> dataMap) {
        InputStream inputStream = null;
        XWPFTemplate template = null;
        try{
            // 加载Word模板
            inputStream = WordUtil.class.getClassLoader().getResourceAsStream(templatePath);
//            inputStream = new FileInputStream(templatePath);
            if(inputStream == null){
                throw new RuntimeException("输入文件为空: "+templatePath);
            }
            template = XWPFTemplate.compile(inputStream).render(dataMap);
            // 输出
            template.write(new FileOutputStream(outFileName));

        }catch (Exception e){
            log.error("word生成失败："+ ExceptionUtils.getStackTrace(e));
            throw new RuntimeException(e);
        }finally {
            PoitlIOUtils.closeQuietlyMulti(inputStream, template);
        }
    }


    public static void main(String[] args) throws Exception {
//        String templatePath = "/Users/wuhanxue/Downloads/质量评价报告模板.docx";
        String templatePath = "/Users/wuhanxue/Downloads/template.docx";
        String outputPath = "/Users/wuhanxue/Downloads/output.docx";

        // 加载Word模板
        InputStream inputStream = new FileInputStream(templatePath);

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("company", "贵州万峰林智慧文旅有限公司");
        dataMap.put("systemName", "数据中台");

        RowRenderData row0 = Rows.of("姓名", "学历").textColor("FFFFFF")
                .bgColor("4472C4").center().create();
        RowRenderData row1 = Rows.create("李四", "博士");
        dataMap.put("table", Tables.create(row0, row1));

        // 生成模板文件
        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(dataMap);
        template.writeAndClose(new FileOutputStream(outputPath));



    }


}
